/**
 * Classe de gestion des reunions
* @author I.T. Works.
* @date 18/12/2011
* @version 1.0
*/

package org.itworks.biodev.gui.panels;

import java.awt.event.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;

import org.itworks.biodev.gui.*;
import org.itworks.biodev.model.*;
import org.itworks.helpers.*;
import org.itworks.helpers.gui.*;

public class OrdersPanelView extends JPanel implements Observer {
		
	/* Observer constants */
	public static final int FILL_ORDERS_TABLE = 1;
	public static final int FILL_ORDER_DETAILS_TABLE = 2;
	public static final int FILL_ORDER_ID_LABEL = 3;

	/**
	 * 
	 */
	private static final long serialVersionUID = 3924521482317669382L;

	private static OrdersPanelView ordersPanel = null;
	
	private OrdersPanelControler controler;
	private MainWindowView parent;

    private javax.swing.JButton createNewOrderButton;
    private javax.swing.JButton deleteSelectedOrdersButton;
    private com.toedter.calendar.JDateChooser dateChooser;
    private javax.swing.JLabel dateLabel;
    private javax.swing.JButton filterButton;
    private javax.swing.JLabel idLabel;
    private javax.swing.JTextField idTextField;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane meetingsListScrollPane;
    private javax.swing.JScrollPane meetingsListScrollPane1;
    private javax.swing.JLabel orderDetailsTitleLabel;
    private javax.swing.JTable ordersListTable;
    private javax.swing.JLabel ordersTitleLabel;
    private javax.swing.JTable productsListTable;
    private javax.swing.JLabel totalLabel;
    private javax.swing.JTextField totalTextField;
	
    /**Constructeur de la classe */
	private OrdersPanelView(MainWindowView parent, OrdersPanelControler controler) {
		this.parent = parent;
		this.controler = controler;
		this.controler.getModel().addObserver(this);
		initComponents();
		initHandlers();
		
		controler.viewLoaded();
	}
	
	/**Agencement des onglets et boutons */
    private void initComponents() {

        ordersTitleLabel = new javax.swing.JLabel();
        dateLabel = new javax.swing.JLabel();
        idLabel = new javax.swing.JLabel();
        idTextField = new javax.swing.JTextField();
        filterButton = new javax.swing.JButton();
        createNewOrderButton = new javax.swing.JButton();
        deleteSelectedOrdersButton = new javax.swing.JButton();
        meetingsListScrollPane = new javax.swing.JScrollPane();
        ordersListTable = new javax.swing.JTable();

        totalLabel = new javax.swing.JLabel();
        totalTextField = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        orderDetailsTitleLabel = new javax.swing.JLabel();

        meetingsListScrollPane1 = new javax.swing.JScrollPane();
        productsListTable = new javax.swing.JTable();
        dateChooser = new com.toedter.calendar.JDateChooser();


        ordersTitleLabel.setFont(new java.awt.Font("Trebuchet MS", 1, 18));
        ordersTitleLabel.setText("Commandes");

        dateLabel.setText("Date :");

        idLabel.setText("ID commande :");

        filterButton.setText("Filtrer");


        createNewOrderButton.setText("Creer une commande");
        deleteSelectedOrdersButton.setText("Suppression multiple");

        ordersListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null}
            },
            new String [] {
                "Identifiant", "Date", "Quantite totale", "Prix total", "Modifier", "Annuler"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        
        ordersListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        
        ordersListTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        meetingsListScrollPane.setViewportView(ordersListTable);

        totalLabel.setText("Total :");
        totalLabel.setVisible(false);
        totalTextField.setVisible(false);

        orderDetailsTitleLabel.setVisible(false);
        orderDetailsTitleLabel.setFont(new java.awt.Font("Trebuchet MS", 1, 18));
        orderDetailsTitleLabel.setText("Commande X");

        productsListTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        meetingsListScrollPane1.setViewportView(productsListTable);
        productsListTable.setVisible(false);


        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(meetingsListScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1456, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(orderDetailsTitleLabel)

                        .addGap(18, 18, 18)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addContainerGap(922, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(orderDetailsTitleLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(meetingsListScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(totalLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(totalTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(meetingsListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1468, Short.MAX_VALUE)
                    .addComponent(ordersTitleLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dateLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                        .addComponent(idLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(filterButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 844, Short.MAX_VALUE)

                        .addComponent(deleteSelectedOrdersButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                        
                        .addComponent(createNewOrderButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ordersTitleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(dateLabel)

                        .addComponent(idLabel)
                        .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(filterButton)
                        .addComponent(deleteSelectedOrdersButton)
                        .addComponent(createNewOrderButton))
                    .addComponent(dateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(meetingsListScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(totalTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(totalLabel))
                .addGap(35, 35, 35))
        );
    }// </editor-fold>

    /** Gestion du comportement des boutons*/
	private void initHandlers() {
		this.createNewOrderButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				try {
					controler.createNewOrderButtonActionPerformed(actionEvent);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		
		this.deleteSelectedOrdersButton.addActionListener(new ActionListener() {
			
			
			public void actionPerformed(ActionEvent actionEvent) {
				Vector<Integer> selectedIndexes = new Vector<Integer>();
				/* Pour chaque ligne */
				for(int i = 0; i < ordersListTable.getRowCount(); i++) {
					/* Si la case est coch�e */
					if(ordersListTable.getValueAt(i, 5).toString().equals("true")) {
						selectedIndexes.add(Integer.parseInt(ordersListTable.getValueAt(i, 0).toString()));
					}
				}
				controler.deleteSelectedOrdersButtonActionPerformed(actionEvent, selectedIndexes);
			}
		});
		
		this.ordersListTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent listSelectionEvent) {
				// TODO Auto-generated method stub7
				
				try {
					Order selectedOrder;
					int selectedRow = ordersListTable.getSelectedRow();
					if(selectedRow > -1) {
						int selectedIndex = Integer.parseInt(ordersListTable.getValueAt(selectedRow, 0).toString());
						if(selectedIndex > -1) {
							selectedOrder = OrderTable.getInstance().find(selectedIndex);

							controler.productListTableValueChanged(listSelectionEvent, selectedOrder);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		
		this.filterButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				try {
					controler.filterButtonActionPerformed(actionEvent,dateChooser, idTextField.getText());
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});

	}
	
	
	public static OrdersPanelView getInstance(MainWindowView parent) {
		if(ordersPanel == null) {
			ordersPanel = new OrdersPanelView(parent, new OrdersPanelControler(new OrdersPanelModel()));
		}
		return ordersPanel;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable srcObject, Object object) {
		MVCNotification notification = (MVCNotification)object;
		int reason = notification.getReason();
		
		switch(reason) {
		case FILL_ORDERS_TABLE:
			// todo.
			try {
				fillOrdersTable( (Vector<Order>)notification.getObject() );
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case FILL_ORDER_DETAILS_TABLE:
			try {
				fillOrderDetailsTable((Vector<ProductOrder>)notification.getObject());
				productsListTable.setVisible(true);
				totalLabel.setVisible(true);
				totalTextField.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case FILL_ORDER_ID_LABEL:
			try {
				orderDetailsTitleLabel.setText((String)notification.getObject());
				orderDetailsTitleLabel.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}
	
	/**Remplissage de la table donnant les details d'une commande*/
	private void fillOrderDetailsTable(Vector<ProductOrder> products) throws Exception {
		DefaultTableModel model = new javax.swing.table.DefaultTableModel(
	               new Object [][] {
	               },
	               new String [] {
	                   "Produit", "Quantite", "Prix unitaire", "Prix total"
	               }
	           ) {
	               Class[] types = new Class [] {
	               		java.lang.String.class, java.lang.Integer.class, java.lang.Float.class, java.lang.Float.class
	               };
	               boolean[] canEdit = new boolean [] {
	                   false, false, false, false
	               };

	               public Class getColumnClass(int columnIndex) {
	                   return types [columnIndex];
	               }

	               public boolean isCellEditable(int rowIndex, int columnIndex) {
	                   return canEdit [columnIndex];
	               }
	           };
	           
	   		productsListTable.setModel(model);
			
	   		// Remplissage du tableau productsListTable	et du total de la commande
	   		Float totalPriceOrder=(float) 0;
			
			for (int i=0 ; i<products.size() ; i++) 
			{
				Vector<Object> rowData = new Vector<Object>();
				ProductOrder currentProdutOrder = products.get(i);
				rowData.add(products.get(i).getProduct().getLabel());
				rowData.add(currentProdutOrder.getQuantity());
				rowData.add(currentProdutOrder.getProduct().getPrice());
				Float totalPrice = currentProdutOrder.getProduct().getPrice() * currentProdutOrder.getQuantity();
				rowData.add(totalPrice);
				
				model.addRow(rowData);
				
				totalPriceOrder = totalPriceOrder + totalPrice;
			}	
			this.totalTextField.setText(totalPriceOrder.toString());
	}

	/**Remplissage de la table des commandes*/
	private void fillOrdersTable(Vector<Order> orders) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		DefaultTableModel model = new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Identifiant", "Date", "Quantite totale", "Prix total", "Modifier", "Annuler"
            }
        ) {
			
			private static final long serialVersionUID = -758028855472131221L;
			
			Class[] types = new Class [] {
	                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Float.class, java.lang.String.class, Boolean.class
	            };

	            public Class getColumnClass(int columnIndex) {
	                return types [columnIndex];
	            }
	            
			boolean[] canEdit = new boolean [] {
                false, false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
	        
		};
		
		ordersListTable.setModel(model);
		
		for(Order o : orders) {
			Vector<Object> rowData = new Vector<Object>();
			rowData.add(o.getId());
			rowData.add(o.getDate().toLocaleString());
			rowData.add(o.getTotalQuantity());
			rowData.add(o.getTotalPrice());
			rowData.add("Modifier");
			new ButtonColumn(ordersListTable, new AbstractAction() {

				/**
				 * 
				 */
				private static final long serialVersionUID = 5911305847353251182L;

				@Override
				public void actionPerformed(ActionEvent actionEvent) {
					// TODO Auto-generated method stub
					int selectedIndex = ordersListTable.getSelectedRow();
					controler.buttonColumnOrdersActionPerformed(actionEvent, selectedIndex);
				}
				
			}, 4);
			rowData.add(new Boolean(false));
			model.addRow(rowData);
		}	
	}
}
